package jwtAuth

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var jwtSecret = []byte("vrv123456") // 加密密钥

// Claims Claims结构体定义在token中携带的信息
type Claims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

// GenerateToken 生成 JWT Token 的函数
func GenerateToken(username string) (string, error) {
	claims := Claims{
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			IssuedAt: jwt.NewNumericDate(time.Now()),
			Issuer:   "go-jwt-demo", // 自定义签发者
		},
	}
	//ExpiresAt: jwt.NewNumericDate(time.Now().Add(2 * time.Hour)), // Token 两小时后过期

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	return token.SignedString(jwtSecret)
}

// ParseToken 解析和校验Token的函数
func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}
	return nil, err
}

// ApiAuthMiddleware JWT验证中间件
func ApiAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			log.Printf("请求头中缺少Authorization")
			c.JSON(http.StatusUnauthorized, gin.H{"code": -1, "msg": "请求头中缺少Authorization"})
			c.Abort()
			return
		}

		// 通常格式为 Bearer token_string
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			log.Printf("Authorization格式错误, 应为 Bearer token_string,当前token为: %s", authHeader)
			c.JSON(http.StatusUnauthorized, gin.H{"code": -1, "msg": "Authorization格式错误"})
			c.Abort()
			return
		}

		claims, err := ParseToken(parts[1])
		if err != nil {
			log.Printf("无效的Token,当前token为: %s", parts[1])
			c.JSON(http.StatusUnauthorized, gin.H{"code": -1, "msg": "无效的Token"})
			c.Abort()
			return
		}

		// 将当前用户名存入上下文中
		c.Set("username", claims.Username)

		c.Next()
	}
}
